package utility;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.LinkedList;

import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.extensions.When;

import database.Database;
import database.SqlWrapper;

public final class GooglePoster{

	private final static String USR = "stcal@mysimpatico.com";
	private final static String PSW = "19gleich";
	private final static String URL = "http://www.google.com/calendar/feeds/stcal@mysimpatico.com/private/full";
	private final static String GOOGLE_POSTING_TITLE = "STCAL Posting";
	private final static String POST_MSG = " have been posted.";

	private GooglePoster(){}

	/** Post recorded sessions to Google Calendar such that they show as events in the time line. 
	 * The title of the event will be the activity name, while the content will include a uniquely identifying ID.
	 * Once posted, only the start time and end time may be modified. For deletion, the respective record must be
	 * deleted from the database to avoid synchronization issues.
	 * 
	 * */
	public static void post2Google() throws Exception{
		final CalendarService myService = new CalendarService(GOOGLE_POSTING_TITLE);
		final URL postUrl = new URL(URL);
		myService.setUserCredentials(USR, PSW);
		final LinkedList<CalendarEventEntry> entries = new LinkedList<CalendarEventEntry>();
		final LinkedList<Timestamp> startTimes = new LinkedList<Timestamp>();
		final ResultSet toPost = Database.getUnpostedSessions();
		int i = 0;
		while (toPost.next() && i < 50){
			Timestamp startTime = Timestamp.valueOf(toPost.getObject(1).toString());
			Timestamp endTime = Timestamp.valueOf(toPost.getObject(2).toString());
			int activityId = toPost.getInt(3);

			if (endTime.getTime() - startTime.getTime() < Constants.MM_MILLIS*4) continue;
			final CalendarEventEntry newEntry = new CalendarEventEntry();
			newEntry.setTitle(new PlainTextConstruct(Database.getActivityName(activityId)));
			i++;
			final When eventTimes = new When();
			eventTimes.setStartTime(new DateTime(startTime));
			eventTimes.setEndTime(new DateTime(endTime));
			newEntry.addTime(eventTimes);
			newEntry.setContent(new PlainTextConstruct(Double.toString(startTime.getTime()*-1)));
			entries.add(newEntry);
			startTimes.add(startTime);
		}
		final Statement st = toPost.getStatement();
		final Connection con = st.getConnection();
		final Timestamp[] times = startTimes.toArray(new Timestamp[0]);
		int counter = 0;
		for (CalendarEventEntry newEntry : entries){
			myService.insert(postUrl, newEntry);
			st.executeUpdate(SqlWrapper.update(Database.recordedSessionsTable, Database.postIdColumn, (int) times[counter].getTime(), Database.sessionStartTimeColumn, times[counter]));
			counter++;
		}
		st.close();
		con.close();
		throw new DisplayUpdateException( counter + POST_MSG);
	}

	/**
	 *  Updates database records with start and end times of previously posted sessions to Google Calendar *
	 *  
	 **/
	/*
	public static void syncGoogleRecords() throws IOException, ServiceException{
		final URL feedUrl  = new URL(URL);
		final Query query = new Query(feedUrl);
		final long n;
		final CalendarService myService = new CalendarService(GOOGLE_SYNC);
		myService.setUserCredentials(USR, PSW);

		try {
			if (n == 0) throw new DisplayUpdateException("No posting done yet.");
		}
		catch(RuntimeException e){
			throw new DisplayUpdateException(0 + UPDATE_MSG);
		}


		int updateCount = 0;
		for (long i=0; i<n; i++){
			query.setFullTextQuery(Long.toString(i));
			CalendarEventFeed myResultsFeed = myService.query(query, CalendarEventFeed.class);
			if (myResultsFeed.getEntries().size() > 0) {
				  CalendarEventEntry firstMatchEntry = (CalendarEventEntry)
				      myResultsFeed.getEntries().get(0); 
				  long startTime = firstMatchEntry.getTimes().get(0).getStartTime().getValue();
				  long endTime = firstMatchEntry.getTimes().get(0).getEndTime().getValue();
				  	Constants.db.connectToDatabase();
				  	if (Constants.db.updateTimes((int) i, Constants.getCurrentTime(startTime), Constants.getCurrentTime(endTime))) updateCount++; // search in database
			}
		}
		Constants.db.disconnectFromDatabase();
		throw new DisplayUpdateException(updateCount + UPDATE_MSG);
	}*/
}